package com.hyy.backend.controller;

import com.hyy.backend.common.Result;
import com.hyy.backend.entity.Knowledge;
import com.hyy.backend.service.KnowledgeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/knowledge")
public class KnowledgeController {

    @Autowired
    private KnowledgeService knowledgeService;

    @PostMapping("/publish")
    public Result<String> publish(@RequestBody Knowledge knowledge) {
        try {
            if (knowledge.getUserId() == null ||
                    knowledge.getTitle() == null ||
                    knowledge.getContent() == null ||
                    knowledge.getTypeId() == null ||
                    knowledge.getPostType() == null) {
                return Result.error("缺少必要字段");
            }

            boolean success = knowledgeService.publishKnowledge(knowledge);
            return success ? Result.success("发布成功") : Result.error("发布失败，数据库写入异常");

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("服务器内部错误：" + e.getMessage());
        }
    }

    @GetMapping("/user/{userId}")
    public Result<List<Knowledge>> getUserKnowledge(@PathVariable Integer userId) {
        try {
            List<Knowledge> list = knowledgeService.getUserKnowledge(userId);
            return Result.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取用户帖子失败：" + e.getMessage());
        }
    }
}
